package com.cyx.netty.gateway.handler;

import com.cyx.netty.gateway.client.NettyRouterTransportService;
import com.cyx.netty.gateway.support.DefaultServerWebExchange;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class ServiceChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter {

    private NettyRouterTransportService routerService;

    public ServiceChannelInboundHandlerAdapter(
        NettyRouterTransportService routerService) {
        this.routerService = routerService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        log.info("current thread: "+Thread.currentThread().getName()+"\n");
        FullHttpRequest request = null;
        if (msg instanceof FullHttpRequest){
            request = (FullHttpRequest) msg;
        }
        routerService.transport(new DefaultServerWebExchange(request,ctx));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)  {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  {
        cause.printStackTrace();
        ctx.close();
    }
}
